#include <httplib.h>
#include <bitset>
#include <vector>
#include <nlohmann/json.hpp>

using namespace httplib;
using json = nlohmann::json;

std::vector<int> find_duplicates(const std::vector<int> &data)
{
    std::bitset<10000> bitmap; // 支持0-9999的数字
    std::vector<int> duplicates;

    for (int num : data)
    {
        if (num < 0 || num >= 10000)
            continue; // 安全边界检查

        if (bitmap.test(num))
        {
            duplicates.push_back(num);
        }
        else
        {
            bitmap.set(num);
        }
    }
    return duplicates;
}

int main()
{
    Server svr;

    // 查找重复项服务
    svr.Post("/find-dups", [](const Request &req, Response &res)
             {
        try {
            auto json_body = json::parse(req.body);
            auto data = json_body["data"].get<std::vector<int>>();
            auto duplicates = find_duplicates(data);
            
            json response;
            response["duplicates"] = duplicates;
            res.set_content(response.dump(), "application/json");
        } catch (const std::exception& e) {
            res.status = 400;
            res.set_content("{\"error\":\"Invalid input\"}", "application/json");
        } });

    // 健康检查端点
    svr.Get("/health", [](const Request &req, Response &res)
            { res.set_content("{\"status\":\"OK\"}", "application/json"); });

    std::cout << "C++ service running on port 8081\n";
    svr.listen("0.0.0.0", 8081);
}